package com.spaymallcommon;


import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 验签工具
 */

public class SignatureUtil {

    /**
     * 微信公众号验签
     * @param token
     * @param signature
     * @param timestamp
     * @param nonce
     * @return
     */
    public static boolean check(String token,String signature,String timestamp,String nonce)  {
        String[] arr = new String[]{token,timestamp,nonce};
//        字典序排序
        sort(arr);

        StringBuilder str = new StringBuilder();
        for (String s : arr) {
            str.append(s);
        }
        //消息摘要
        MessageDigest md;
        String temStr = null;
        try {
            md = MessageDigest.getInstance("SHA-1");
            byte[] digest = md.digest(str.toString().getBytes());
            temStr = byteToStr(digest);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }

        /** signature.toUpperCase()将字符串的每一字符转大写  signature是十六进制字符串 */
        return temStr!=null && temStr.equals(signature.toUpperCase());



    }


    public static String byteToStr(byte[] byteArray) {
        StringBuilder stringBuilder = new StringBuilder();
        for (byte b : byteArray) {
            stringBuilder.append(byteToHexStr(b));
        }

        return new String(stringBuilder);
    }

    public static String byteToHexStr(byte mByte) {
        char[] Digit = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        char[] tempArr = new char[2];
        tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
        tempArr[1] = Digit[mByte & 0X0F];

        return new String(tempArr);
    }


    /**
     * 进行字典序排序
     * @param arr
     */

    public static void sort(String[] arr){

        for (int i = 0; i < arr.length-1; i++) {
            for (int j = i+1; j < arr.length; j++) {
                if (arr[j].compareTo(arr[i]) < 0){
                    String temp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;
                }
            }

        }
    }

}
